package com.cloudjan.springcloud.lb;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 自定义负载均衡算法
 */
@Component
@Slf4j
public class MyLB implements Loadbalance{

    private AtomicInteger atomicInteger = new AtomicInteger(0);

    @Override
    public ServiceInstance instances(List<ServiceInstance> serviceInstances) {
        int index = getAndIncrement()%serviceInstances.size();
        return serviceInstances.get(index);
    }

    private int getAndIncrement(){
        int current;
        int next;
        do {
            current = atomicInteger.get();
            next = current>=Integer.MAX_VALUE?0:current+1;
        } while (!atomicInteger.compareAndSet(current,next));
        log.info("访问次数=="+next);
        return next;
    }
}
